/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: Wireless_Dummy.cpp,v 1.5 2009-06-17 10:09:54 morsko Exp $
 *
 * \file
 * \brief Wireless interface usage example as Dummy module.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 * - None.
 *
 * Provides Interfaces:
 * - Wireless
 *
 * Needs Interfaces:
 * - None.
 *
 * General information:
 * - None.
 * 
 ******************************************************************************
 */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "WirelessServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to 1
static int verbose = 1;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::Wireless;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************

// Local configuration structure
struct SLocalConfig {
  SLocalConfig()
    : myparameter("SomeDefaultValue") {}
  std::string myparameter;
};
//*****************************************************************************

// Local configuration here. (Encapsulated in struct to make it easier
// to pass around)
SLocalConfig localConfig;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(1,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(1,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//*****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tDummy_Dummy [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

static int wirelessWatch(CWirelessServer *ws)
{
  CWirelessData wd;

  EMaCIError e;
  while(run) {
    e = ws->WaitCommand(wd, 1000);
    if (e == KMaCIOK) {
      const TCommand *c = wd.GetCommand();
      if (c) {

        dPrint(1,"Got command: %d, data %d", c->cmd, c->data);
      } else {
        dPrint(1,"Got Command, but no Command element present???");

      }
    }
  }
  
  return 0;
}
//*****************************************************************

void ConstructWirelessFingerprint(CWirelessData &wd)
{
  const int fpcount = 1 + (random() % 10);
  wd.Reset();
  
  dPrint(1,"\n\nBegin construction:");
  const MaCI::Common::TTimestamp ts;
  dPrint(1,"Adding Timestamp");
  wd.SetTimestamp(ts);

  for(int i=0; i < fpcount; ++i) {
    const unsigned int nodeid = random();
    const int signal_dbm = -(random() % 95);

    const TNodeSignal ns(nodeid, signal_dbm);
    const TNodeRange nr(nodeid, -0.50 * signal_dbm, -0.5*signal_dbm*0.001);
    const TNodePosition np(nodeid, 
                           signal_dbm * signal_dbm, 
                           signal_dbm * signal_dbm/10.00, 
                           signal_dbm * signal_dbm*10.00);

   

    dPrint(1,"Adding TNodeSignal:");
    ns.Print(1);
    wd.AddNodeSignal(ns);

    dPrint(1,"Adding TNodeRange:");
    nr.Print(1);
    wd.AddNodeRange(nr);

    dPrint(1,"Adding TNodePosition:");
    np.Print(1);
    wd.AddNodePosition(np);
  }

}
//*****************************************************************

static int ExecuteModule(gimi::GIMI &g)
{
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);
  CWirelessServer ws(&mcs, 0, "DummyWireless", "Dummy");
  ownThreadHandle wirelessWatchThread;

  // Construct data object.
  CWirelessData wd;
  wd.CreateInternalBinBag();
  
  // Set GroupName for MaCICtrlServer and Instance for AlarmServer.
  mcs.SetGroupName(macigroup);
  ws.SetInterfaceInstanceName("DummyInstance");
  
  // Init random number generator
  srandom(time(NULL));
  
  // Open and execute
  if (ws.Open() == KMaCIOK) {
    // Create command listening thread
    wirelessWatchThread = ownThread_Create((void*)wirelessWatch, &ws);

    // Now operate.
    while(run) {
      ConstructWirelessFingerprint(wd);
      ws.SendWirelessEvent(wd);
      ownSleep_ms(1000);
    }
    
    // Wait for command thread to terminate.
    ownThread_Join(wirelessWatchThread, NULL);

  } else {
    dPrint(1,"Failed to open CWirelessServer instance! Fatal.");
    return -1;

  }
  
  return 0;
}
//*****************************************************************************

static bool ParseConfiguration(SLocalConfig &aConf,
                               const std::string &aConfigFile)
{ 
  gim::CSettings settings;
  bool result = settings.ReadSettingsXMLFile(aConfigFile);
  
  // Was the file succesfully parsed?
  if (result) {
    bool r;

    // Set basekey.
    settings.SetBaseKey("My_Module_Name");

    // Start extracting parameters. Duplicate this to extract
    // more. The print is just for verbalizing the output, so use it
    // if you want.
    r = settings.GetValue("myparameter", aConf.myparameter);
    if (r) { dPrint(3,"Got configuration value for 'MyParameter' = '%s'", aConf.myparameter.c_str()); } 
    else { dPrint(3,"No configuration value for 'MyParameter'"); }

    // Modify 'result', for example, if you want to force some parameters to
    // exists or pass some other quality check.
  }
  
  return result;
}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(4);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.5 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(3,"Using configuration file: '%s'", optarg);
      if (ParseConfiguration(localConfig, configurationFile) == true) {
        dPrint(4,"Succesfully parsed configuration file '%s'", optarg);
      } else {
        dPrint(1,"Parsing configuration failed! Fatal error. Exit.");
        exit(1);
      }
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(3,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
 * 
 * $Log: not supported by cvs2svn $
 * Revision 1.4.2.1  2009-06-16 09:20:04  morsko
 * lots of changes
 *
 * Revision 1.4  2009-05-13 07:18:23  amaula
 * Doxygens file tag parameter removed, as no parameter means 'document this file'
 *
 * Revision 1.3  2008-12-01 11:59:51  amaula
 * Some typofixes.
 *
 * Revision 1.2  2008-12-01 11:08:12  amaula
 * Simple dummy added.
 *
 * Revision 1.1  2008-12-01 10:07:01  amaula
 * Base implementations
 *
 * Revision 1.2  2008-12-01 10:01:31  amaula
 * Cleanup
 *
 * Revision 1.1  2008-12-01 10:00:00  amaula
 * Added pure dummy module.
 *
 *****************************************************************************/
//*****************************************************************************
//*****************************************************************************


